<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>状态模式</title>
</head>

<body>
    <script>
        const Light = function () {
          this.state = 'off';
          this.button = null;
        };

        Light.prototype.init = function () {
          this.OffLightState = new OffLightState(this);
          this.weakLightState = new WeakLightState(this);
          this.strongLightState = new StrongLightState(this);
          const button = document.createElement('button'),
            self = this;
          button.innerHTML = '开关';
          this.button = document.body.appendChild(button);
          this.currState = this.OffLightState; //设置当前状态
          this.button.addEventListener('click', () => {
    self.currState.buttonWasPressed();
  });
        };

        Light.prototype.setState = function (newState) {
          this.currState = newState;
        };

        // OffLightState
        let OffLightState = function (light) {
          this.light = light;
        };

        OffLightState.prototype.buttonWasPressed = function () {
          console.log('弱光');
          this.light.setState(this.light.weakLightState); //把状态切到weakLightState
        };

        // WeakLightState
        let WeakLightState = function (light) {
          this.light = light;
        };

        WeakLightState.prototype.buttonWasPressed = function () {
          console.log('强光');
          this.light.setState(this.light.strongLightState); //把状态切到weakLightState
        };

        // StrongLightState
        let StrongLightState = function (light) {
          this.light = light;
        };

        StrongLightState.prototype.buttonWasPressed = function () {
          console.log('关灯');
          this.light.setState(this.light.OffLightState);
        };

        new Light().init();
    </script>
</body>

</html>